package com.mahjong.server.manager;

import java.util.Queue;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.mahjong.server.common.Common;
import com.mahjong.server.model.Player;
import com.mahjong.server.service.UserService;

/**
 * 心跳管理
 * 
 * @author Simple
 * @date 2013-4-27 上午10:19:56
 * @Description TODO
 */
@Component
public class HeartBeatManager extends Thread {

  private Logger log=Logger.getLogger(this.getClass());

  @Autowired
  private OnlineManager onlineManager;

  @Autowired
  private UserService userService;

  @Override
  public void run() {
    // TODO Auto-generated method stub
    Queue<Player> list=onlineManager.getAllOnlinePlayer();
    for(Player p: list) {
      p.heartbeat();// 心跳
      checkPlayerIsAlive(p);
    }
  }

  /**
   * 检测用户是否活着
   * 
   * @param p
   */
  private void checkPlayerIsAlive(Player p) {
    if(p.getIdleTime() > Common.IDLE_TIME) {// 空闲
      onlineManager.removeOnline(p);// 超出空闲时间，从在线列表移除玩家
      log.debug(String.format("玩家{%s}超出空闲时间,从在线列表移除~!", p));
      userService.save(p.getUser());
      log.debug("保存用户信息");
    }
  }
}
